package cn.jhc.social.qq.api.impl;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import cn.jhc.social.qq.api.NoOpenidException;
import cn.jhc.social.qq.api.OpenidOperation;

public class OpenidTemplate extends AbstractQQOperations implements
		OpenidOperation {
	private final static Pattern OPENID_PATTERN = Pattern.compile("\"openid\":\"([\\w]+)\"");
	private final RestTemplate restTemplate;
	public OpenidTemplate(RestTemplate restTemplate,boolean isAuthorized) {
		super(isAuthorized);
		this.restTemplate = restTemplate;
	}

	@Override
	public String getOpenid() {
		requireAuthorization();
		ResponseEntity<String> response = restTemplate.getForEntity(buildUri("oauth2.0/me"), String.class);
		Matcher matcher = OPENID_PATTERN.matcher(response.getBody());
		if(matcher.find()) {
			return matcher.group(1);
		}
		else {
			throw new NoOpenidException();
		}
	}
}
